﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using JwtAuthorizationSample_.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace JwtAuthorizationSample_.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly IOptions<JwtSettings> _optionAccessor;
        public ValuesController(IOptions<JwtSettings> optionAccessor)
        {
            this._optionAccessor = optionAccessor;
        }
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            if (!ModelState.IsValid)
            {
                return "错误请求";
            }
            var claims = new List<Claim>() { new Claim(ClaimTypes.Name, "Zj"), new Claim(ClaimTypes.Role, "admin") };
            var jwtSettings = _optionAccessor.Value;
            var credentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)), SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(
                jwtSettings.Issuer,
                jwtSettings.Audience,
                claims,
                DateTime.Now,
                DateTime.Now.AddMinutes(30),
                credentials);
            //return Json(new { Token = new JwtSecurityTokenHandler().WriteToken(jwtToken) });
            return new JwtSecurityTokenHandler().WriteToken(jwtToken);
        }

        // POST api/values
        [HttpPost]
        public string Post([FromBody]string value)
        {
            if (!ModelState.IsValid)
            {
                return "错误请求";
            }
            var claims = new List<Claim>() { new Claim(ClaimTypes.Name, "Zj"), new Claim(ClaimTypes.Role, "admin") };
            var jwtSettings = _optionAccessor.Value;
            var credentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)), SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(
                jwtSettings.Issuer,
                jwtSettings.Audience,
                claims,
                DateTime.Now,
                DateTime.Now.AddMinutes(30),
                credentials);
            //return Json(new { Token = new JwtSecurityTokenHandler().WriteToken(jwtToken) });
            return new JwtSecurityTokenHandler().WriteToken(jwtToken);
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
